<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use App\Models\Income;
use App\Models\Trade;
use App\Models\User;
use Illuminate\Http\Request;
use Excel;
use DB;
use HttpRequest;
use Curl;
use HttpClient;
use Illuminate\Support\Facades\Mail;


class TestController extends Controller
{

    public $ret=array();

    /**
     * 计算代理收入
     */

    public function index()
    {
        DB::listen(function($sql){
//dump($sql);
        });
        $data = DB::table("trades")->where("type","!=","balance")->whereBetween("created_at",[date("Y-m-d"),date("Y-m-d",time()+24*3600)])->get();
//        die;
        $time= date("Y-m-d H:i:s");
        $mm=array();
        foreach ($data as $val){
            $m= -$val->profit;
            $info = User::where("tranid",$val->tranid)->first(["sorts"]);
            $sorts = $info->sorts;
            $aid= explode("-",$sorts);

            unset($aid[0]);
            $list = Admin::whereIn("id",$aid)->get(["percent"]);
//            dd($list);
            foreach ($list as $key =>$v){
                if(isset($list[$key+1]->percent)){
                    if($list[$key+1]->percent == $v->percent){
                        $income=0;
                        $mm[]=array('aid'=>$aid[$key+1],'tid'=>$val->id,'percent'=>$v->percent,'money'=>'0','next'=>$list[$key+1]->percent,'created_at'=>$time);
                    }else{
                        $income=($v->percent - $list[$key+1]->percent)*$m/100;
                        $mm[]=array('aid'=>$aid[$key+1],'tid'=>$val->id,'percent'=>$v->percent,'created_at'=>$time,'next'=>$list[$key+1]->percent,'money'=>$income);
                    }
                }else{
                    $income=intval($v->percent)*$m/100;
                    $mm[]=array('aid'=>$aid[$key+1],'tid'=>$val->id,'percent'=>$v->percent,'created_at'=>$time,'next'=>0,'money'=>$income);
                    Admin::where("id",$aid[$key+1])->increment("totlemoney",$m);
                }

                Admin::where("id",$aid[$key+1])->increment("money",$income);
            }
        }
        Income::insert($mm);
    }

    public function reset(){
       $list =  Admin::get(['id','totlemoney']);

        $this->setlog(json_encode($list),'系统自动重置代理业绩');

        Admin::update('totlemoney','0');
    }


    public function setlog($data,$content){

        $ip= $_SERVER["REMOTE_ADDR"];
        $insert=array(
            'uid'=>'0',
            'username'=>'系统',
            'ip'=>'0.0.0.0',
            'type'=>'2',
            'content'=>$content,
            'data'=>$data,
            'created_at'=>date("Y-m-d H:i:s")
        );
        DB::table("action_log")->insert($insert);
    }

    public function aaa(Request $request){
        Mail::raw('1111',function ($message){
            $message->subject(config("app.host"));
            $message->to('164445438@qq.com');
        });
    }

    public function testsss(Request $request){
//        dd($this->postcurl("http://agent.test.com/aaa")) ;


        if($request->isMethod("post")){



//            $url = 'https://lp.fxclub.cn/open-account/trade/meta_market?partner_code=CHN227IPB';
        $url = 'http://agent.tonglingdi.cn/aaa?partner_code=CHN227IPB';
            $data='{"password":"liu1995","firstname":"中就","lastname":"王","city[country]":"43","city[city]":"北京",
       "birthdate[day]":"20","birthdate[month]":"10","birthdate[year]":"1995",
       "client_timezone":"-480","acctype":"meta_market",
        "form_id":"forex_landing_view_form","check_js":"",
        "region_id":""}';
            $post_data = json_decode($data,true);

//            $post_data["birthdate"]=$request->birthdate;
//            dd($post_data);
//
//            $post_data["lastname"]=$request->lastname;
//            $post_data["password"]=$request->password;
//            $post_data["firstname"]=$request->firstname;
//            $city=$request->city;
//            $post_data["city[city]"]=$city["city"];
//            $post_data["city[country]"]=$city["country"];
//            $birthdate=$request->birthdate;
//            $post_data["birthdate[day]"]=$birthdate["day"];
//            $post_data["birthdate[month]"]=$birthdate["month"];
//            $post_data["birthdate[year]"]=$birthdate["year"];
//            $post_data["client_timezone"]=$request->client_timezone;
//            $post_data["acctype"]=$request->acctype;
//            $post_data["check_js"]='';
//            $post_data["region_id"]='';
//            $post_data["form_id"]=$request->form_id;



            $post_data["captcha_response"]=$request->captcha_response;
            $post_data["email"]=$request->email;
//            $phone =$request->phone1;
//            $post_data["phone1[country_code]"]=$phone["country_code"];

            $post_data["phone1[country_code]"]= $phone =$request->phone;
            $post_data["forex_protect_min_time"]=$request->forex_protect_min_time;
            $post_data["captcha_sid"]=$request->captcha_sid;
            $post_data["captcha_token"]=$request->captcha_token;
            $post_data["form_build_id"]=$request->form_build_id;
            $post_data["url"]="";

//            $options = array(
//'http'=> array(
//'method'=>'POST',
//    'header'=>"Content-type: multipart/form-data\r\n".
//        "Content-length:".strlen($data)."\r\n" .
//        "Cookie: foo=bar\r\n" .
//        "\r\n",
//'content'=> http_build_query($post_data),
//),
//            );

//            $data='{"email":"145782235@qq.com","password":"liu1995","firstname":"c","lastname":"王","city[country]":"43","city[city]":"北京",
//        "phone1[country_code]":"15819882547","birthdate[day]":"10","birthdate[month]":"10","birthdate[year]":"1995",
//        "form_build_id":"form-7LZ98dyO8s9MIjh9YMzo0y-Rit_Y_EGbCrgFGjmn8Qw","client_timezone":"-480","acctype":"meta_market",
//        "form_id":"forex_landing_view_form","forex_protect_min_time":"SDhU1Xv9WKAqEJlmQo7SR2ev5WtczOxBcGyr2UbkUHc=","check_js":"",
//        "region_id":"","captcha_sid":"4156089","captcha_token":"db6cc0c948db9b0e7206af754d6e76bb","captcha_response":"hcy4q"}';
//        $post_data=json_decode($data,true);

//            $pageContents = HttpClient::quickPost($url, $post_data);
////$result = explode(',', $pageContents);
//            print_r($pageContents);
//            die;

//            $result = file_get_contents($url,false, stream_context_create($options));
//            return $result;

//            dd(($post_data));

//            $ret = HttpClient::from()->post($url,$post_data);
//
////            $http=new HttpClient();
////
////            $pageContents = $http->quickPost($url, $post_data);
//////$result = explode(',', $pageContents);
//            print_r($ret);die;
//
////            $pro = $this->postcurl($url,$post_data);
////        $pdata = json_decode($pro);
//            print_r($pro);
//            die;
            $response = Curl::to($url)
                ->withData( $post_data )
                ->post();

            print_r($response);

        }else{


echo time();
            $response = Curl::to('https://lp.fxclub.cn/api/1/security/captcha/?callback=jQuery111209433767567777742_1492001292383&_='.time())
                ->get();


            $response = $this->getNeedBetween($response,"(",")");

            dump(json_decode($response,true));
            return view("layouts.app",["info"=>json_decode($response,true)]);
        }

    }

    public function getNeedBetween($kw1,$mark1,$mark2){
        $kw=$kw1;
        $st =stripos($kw,$mark1);
        $ed =stripos($kw,$mark2);
        if(($st==false||$ed==false)||$st>=$ed)
            return 0;
        $kw=substr($kw,($st+1),($ed-$st-1));
        return $kw;
    }

    /**
     * curl post
     * @param type $url
     * @return json
     * @author wx
     */
//    public function get_url_contents($url,$post_data='',$header){
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt ( $ch, CURLOPT_POST, 1 );
////        dd($header);
//
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
//        // 把post的变量加上
//        curl_setopt($ch, CURLOPT_POSTFIELDS,  $post_data);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
////        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, POST);
//        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);// 设为TRUE把curl_exec()结果转化为字符串，而不是直接输出
//        $tmpInfo = curl_exec($ch);
////        dd($tmpInfo);
//        curl_close($ch);
//        return $tmpInfo;
//    }

    /**
     * 对象 转 数组
     *
     * @param object $obj 对象
     * @return array
     */
    public function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)$this->object_to_array($v);
            }
        }

        return $obj;
    }


    /**
     * 导入操作记录
     */
    public function import(){

      $ret =   Excel::load(storage_path("test.xls"), function($reader) {

            $data = $reader->toArray();

            $str= '';
            foreach ($data as $key =>$val){
                unset($data[$key][0]);
                $str.= end($data[$key]);
            }
            $html = $this->get_td_array($str);


            $first = explode(":",$html[0][0]);
            $tranid = $first[1];

            unset($html[0]);
            unset($html[1]);
            $data=array();
            $ticket=array();

            foreach ($html as $val){
                if(is_numeric($val[0])){
                    $ticket[]=$val[0];
                    $data[$val[0]]=array(
                        'tranid'=>$tranid,
                        'ticket'=>$val[0],
                        'starttime'=>$val[1],
                        'type'=>$val[2],
                        'size'=>$val[3],
                        'item'=>$val[4],
                        'startprice'=>$val[5],
                        's/l'=>$val[6],
                        't/p'=>$val[7],
                        'endtime'=>$val[8],
                        'endprice'=>$val[9],
                        'commission'=>$val[10],
                        'profit'=>$val[13],
                    );

                }else{
                    break;
                }
            }

           $t =  Trade::whereIn("ticket",$ticket)->get(["ticket"]);
//          dd($ticket);
            if(count($t)){
                foreach ($t as $val){
                    unset($data[$val->ticket]);
                }
                $this->ret=array(
                    'yes'=>count($data),
                    'repeat'=>count($t)
                );
            }else{
                $this->ret=array(
                    'yes'=>count($data),
                    'repeat'=>0
                );
            }

//            dd($data);

            if(!empty($data)){
                Trade::insert($data);
            }

//            return $ret;
        })->get();

        dd($this->ret);
    }

    public function  get_td_array($table) {
          $table = preg_replace("'<table[^>]*?>'si","",$table);
          $table = preg_replace("'<tr[^>]*?>'si","",$table);
          $table = preg_replace("'<td[^>]*?>'si","",$table);
          $table = str_replace("</tr>","{tr}",$table);
          $table = str_replace("</td>","{td}",$table);
          //去掉 HTML 标记
          $table = preg_replace("'<[/!]*?[^<>]*?>'si","",$table);
          //去掉空白字符
          $table = preg_replace("'([rn])[s]+'","",$table);
          $table = str_replace(" ","",$table);
          $table = str_replace(" ","",$table);
          $table = explode('{tr}', $table);
          array_pop($table);
          foreach ($table as $key=>$tr) {
            $td = explode('{td}', $tr);
            array_pop($td);
            $td_array[] = $td;
          }
        return $td_array;
}

    public function postcurl($request_url,$data = array()){


//        $data ='email=1644454%40qq.com&phone=15810882321&form_build_id=form-sJpk0MP-eqBnpTcM_P4NUjB4wy2Se3S-BKaGHcK2vj8&forex_protect_min_time=y56C%2Bk38Q%2B06GBqO1h74fFkBpTV9T91bnVrpTgz%2BJkA%3D&captcha_token=3d1e5dad2292ae6d370911b04f5964ed&captcha_sid=4156328&captcha_response=2thrf&_token=FQos3UW5IQkmElpktpZ1YGlv1w1jQpf9duCrHXig';
//
        $ch = curl_init();
        $res= curl_setopt ($ch, CURLOPT_URL,$request_url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//        curl_setopt ($ch, CURLOPT_HEADER,1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_REFERER, "http://agent.test.com");
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11");
        curl_setopt($ch,CURLOPT_COOKIE,'check_js=f510b7f565b61c8d3de4820aa0065fd929c26241; SESS8540bb458516ebb772467bd23f374de0=57a6a9cd6b4d8c44de099793c7634fc7; liveagent_oref=https://lp.fxclub.cn/open-account/trade/meta_market/?partner_code=CHN227IPB; liveagent_sid=54bbabd6-59a4-42df-865c-384bd1ae3eff; liveagent_vc=2; liveagent_ptid=54bbabd6-59a4-42df-865c-384bd1ae3eff; _qzja=1.1274514553.1492146476104.1492146476104.1492146476104.1492146512079.1492147328931.0.0.0.4.1; _qzjc=1; _qzjto=4.1.0; FxclubPartnerCode=CHN227IPB; _ga=GA1.2.834765454.1492151086; _gat_tealium_0=1; utag_main=v_id:015b6b22ab0c0001cd0411b5c7c00506d004b06500bd0$_sn:1$_ss:0$_pn:2%3Bexp-session$_st:1492153061041$ses_id:1492151085836%3Bexp-session$dc_visit:1$dc_event:2%3Bexp-session$dc_region:eu-central-1%3Bexp-session');

        $result = curl_exec ($ch);
        curl_close($ch);
        return $result;
//        $output = json_decode($output, True);

//        return $output;
    }
}